#!/bin/sh
# set -x

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

MAIN_FILE="${1%.tex}"
OUTPUT_FOLDER="$2"
HTML_SETTINGS="$SCRIPT_DIR/html-plain,fn-in,charset=utf-8" 
ENCODING="-cunihtf -utf8"

mkdir -p $OUTPUT_FOLDER

echo Pre-Build With PDF Latex
pdflatex $MAIN_FILE
bibtex   $MAIN_FILE
pdflatex $MAIN_FILE
pdflatex $MAIN_FILE

echo
echo Build With Latex and TEX4HT
latex $5 '\makeatletter\def\HCode{\futurelet\HCode\HChar}\def\HChar{\ifx"\HCode\def\HCode"##1"{\Link##1}\expandafter\HCode\else\expandafter\Link\fi}\def\Link#1.a.b.c.{\g@addto@macro\@documentclasshook{\RequirePackage[#1,html]{tex4ht}}\let\HCode\documentstyle\def\documentstyle{\let\documentstyle\HCode\expandafter\def\csname tex4ht\endcsname{#1,html}\def\HCode####1{\documentstyle[tex4ht,}\@ifnextchar[{\HCode}{\documentstyle[tex4ht]}}}\makeatother\HCode '$HTML_SETTINGS'.a.b.c.\input ' $MAIN_FILE
#latex $5 '\makeatletter\def\HCode{\futurelet\HCode\HChar}\def\HChar{\ifx"\HCode\def\HCode"##1"{\Link##1}\expandafter\HCode\else\expandafter\Link\fi}\def\Link#1.a.b.c.{\g@addto@macro\@documentclasshook{\RequirePackage[#1,html]{tex4ht}}\let\HCode\documentstyle\def\documentstyle{\let\documentstyle\HCode\expandafter\def\csname tex4ht\endcsname{#1,html}\def\HCode####1{\documentstyle[tex4ht,}\@ifnextchar[{\HCode}{\documentstyle[tex4ht]}}}\makeatother\HCode '$HTML_SETTINGS'.a.b.c.\input ' $MAIN_FILE
#latex $5 '\makeatletter\def\HCode{\futurelet\HCode\HChar}\def\HChar{\ifx"\HCode\def\HCode"##1"{\Link##1}\expandafter\HCode\else\expandafter\Link\fi}\def\Link#1.a.b.c.{\g@addto@macro\@documentclasshook{\RequirePackage[#1,html]{tex4ht}}\let\HCode\documentstyle\def\documentstyle{\let\documentstyle\HCode\expandafter\def\csname tex4ht\endcsname{#1,html}\def\HCode####1{\documentstyle[tex4ht,}\@ifnextchar[{\HCode}{\documentstyle[tex4ht]}}}\makeatother\HCode '$HTML_SETTINGS'.a.b.c.\input ' $MAIN_FILE

echo
echo Do Tex4HT
tex4ht -f/$MAIN_FILE  -i~/tex4ht.dir/texmf/tex4ht/ht-fonts/ $ENCODING
t4ht -f/$MAIN_FILE -d$OUTPUT_FOLDER

echo
echo Run Tidy
tidy -ashtml -utf8 $OUTPUT_FOLDER/$MAIN_FILE.html > $OUTPUT_FOLDER/$MAIN_FILE-tidy.html

echo Run Post Process HTML
$SCRIPT_DIR/post-process-html.py $OUTPUT_FOLDER/$MAIN_FILE-tidy.html > $OUTPUT_FOLDER/$MAIN_FILE-final.html
